import json
from application.config import appSettings
from ..base import BaseModel


class Setting(BaseModel):
    __connection__ = 'postgres'

    __table__ = appSettings.db_code_prefix + 'settings'

    @staticmethod
    def get_cratch_obj(code=''):
        """
            商户刮刮码数字乱码配置
        """
        key = f'scratch_info_{code}'
        setting = Setting.where('type', 3).where('key', key).first()
        if setting is None:
            setting = Setting.create({
                'type': 3,
                'key': key,
                'value': json.dumps({
                    'length_5': 0,
                    'length_6': 0,
                    'length_7': 0,
                    'length_8': 0,
                    'length_9': 0,
                    'length_10': 0,
                    'length_11': 0,
                    'length_12': 0,
                    'length_13': 0,
                    'length_14': 0,
                    'length_15': 0,
                    'length_16': 0,
                    'length_17': 0,
                    'length_18': 0,
                    'length_19': 0,
                    'length_20': 0,
                })
            })
            setting.save()
        # 判断是不是有 12 以上的数据 没有就添加
        set_value = json.loads(setting.value)
        if 'length_13' not in set_value:
            set_value['length_13'] = 0
            set_value['length_14'] = 0
            set_value['length_15'] = 0
            set_value['length_16'] = 0
            set_value['length_17'] = 0
            set_value['length_18'] = 0
            set_value['length_19'] = 0
            set_value['length_20'] = 0

            setting.value = json.dumps(set_value)
            setting.save()

        return setting

    @staticmethod
    def scratch_info(code=''):
        """
            商户刮刮码数字乱码配置
        """
        setting = Setting.get_cratch_obj(code)
        return json.loads(setting.value)

    @staticmethod
    def scratch_code_count(code='', length=5):
        """
            当前位数下的生码量
        """
        scratch_info = Setting.scratch_info(code)
        key = f'length_{length}'
        return int(scratch_info[key])


__all__ = ['Setting']
